package com.zd.ticketing.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zd.common.common.utils.HttpRequestUtil;
import com.zd.common.common.utils.LogUtils;
import com.zd.ticketing.service.ITicketOrderService;

/**
 * @author lishi
 * @date 2018年11月12日 下午7:33:45
 */
@Controller
@RequestMapping("pay")
public class PayController {
	
	@Autowired
	private ITicketOrderService ticketOrderService;
	
	@ResponseBody
	@RequestMapping("unifiedorder")
	public Map<String,Object> unifiedorder(String appid, String openid,String touristJson, HttpServletRequest request) throws Exception {
		Map<String, Object> resultMap = new HashMap<>();
		//TODO 统一下单
		System.out.println( appid + " appid " + openid +  "appid  ");
		LogUtils.info(touristJson);
		resultMap = ticketOrderService.buyTieckts(appid, openid, touristJson, HttpRequestUtil.getIp(request));
		
		return resultMap;
	}
	
	@ResponseBody
	@RequestMapping("goDownAgain")
	public Map<String , String> goDownAgain(Integer orderId, HttpServletRequest request) throws Exception {
		Map<String, String> resultMap = new HashMap<>();
		//TODO 统一下单
		LogUtils.info(orderId);
		resultMap = ticketOrderService.goDownAgain(orderId,  HttpRequestUtil.getIp(request));
		LogUtils.info(resultMap);
		return resultMap;
	}
	
	@ResponseBody
	@RequestMapping("wxPayReturn")
	public String wxPayReturn(HttpServletRequest request) throws Exception {
		try {
			String xmlStr = getXmlStrFromRequest(request);
			ticketOrderService.wxPayReturn(xmlStr);
		} catch (Exception e) {
			e.printStackTrace();
			LogUtils.debug(e.getMessage());
		}
		return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
	}
	
	private String getXmlStrFromRequest(HttpServletRequest request) throws IOException {
		String result = "";
		InputStream inStream = request.getInputStream();
		int _buffer_size = 1024;
		if (inStream != null) {
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			byte[] tempBytes = new byte[_buffer_size];
			int count = -1;
			while ((count = inStream.read(tempBytes, 0, _buffer_size)) != -1) {
				outStream.write(tempBytes, 0, count);
			}
			tempBytes = null;
			outStream.flush();
			//将流转换成字符串
			result = new String(outStream.toByteArray(), "UTF-8");
			LogUtils.debug("result:" + result);
		}
		return result;
	}
	
	
}
